package com.nit.store.util;

import io.jsonwebtoken.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.sql.Date;
import java.util.Map;

/**
 * jwt 工具类
 */
@Component
@Slf4j
public class JwtUtils {
    @Value("${jwt.secret}")
    private String secret;

    //密钥 用于加密生成jwt数据
    @Value("${jwt.secret}")
    private String secretKey ;
    @Value("${jwt.expiration}")
    private Long expiration;

    /**
     * 根据jwt获取 用户uid
     * @param jwt
     * @return 用户uid
     */
    public Long parseJwtGetId(String jwt){
        Long uid = null;
        try{
            JwtParser parser = Jwts.parser();
            //获取数据 claims
            Claims claims = parser.setSigningKey(secret).parseClaimsJws(jwt).getBody();
            uid = Long.parseLong(claims.get("uid").toString());
            return uid;
        }catch (Exception e){
            log.error("jwt解析失败！");
            return null;
        }
    }

    /**
     * 根据jwt数据获取 用户名
     * @param jwt
     * @return
     */
    public String parseJwtGetName(String jwt){
        String username = null;
        try{
            JwtParser parser = Jwts.parser();
            Claims claims = parser.setSigningKey(secret).parseClaimsJws(jwt).getBody();
            username = claims.get("username").toString();
            return username;
        }catch (Exception e){
            log.error("jwt解析失败！");
            return null;
        }
    }


    /**
     * 生成Jwt
     *
     */
    public String createToken(Map<String,Object> claims) {
        String token = Jwts.builder()
                .setHeaderParam(Header.TYPE,Header.JWT_TYPE)
                .setHeaderParam(Header.CONTENT_TYPE,"HS256")
                .setClaims(claims)
                .setExpiration(new Date(System.currentTimeMillis()+expiration*1000))
                .signWith(SignatureAlgorithm.HS256,secretKey)
                .compact();
        System.out.println(token);
        return token;
    }


}
